/**
 * 
 */
//ipPort = '10.58.88.212:8080';

Ext.define('Case.List',{
	extend: 'Ext.tree.Panel',
	alias: 'case.list',

		
	initComponent: function(){
		
		settingServer = Ext.create('server', {});
		settingWin = Ext.create('Ext.window.Window', {
			title: 'Settings',
			closable: true,
			//closeAction: 'hide',
			width: 800,
			height: 400,
			//layout: 'border',
			borderStyle: 'padding:5px;',
			shadown: false,
			modal: true,
			closeAction: 'hide', 
			items: [
			     settingServer
			]
			
		});
		
		var me_list = this;
		me_list.metaData = null;
		me_list.serverStore = Ext.create('Ext.data.Store', {
			model: 'Server'
		});
		
		me_list.serverStore.load();
		Ext.Ajax.request({
			url: 'http://' + ipPort + '/bpcmetadata',
			method: 'GET',
			success: function(response){
				me_list.metaData = Ext.decode(response.responseText);
			}
		});
		me_list.setLoading('Loading');
		me_list.caseStore = Ext.create('Ext.data.TreeStore',{
			proxy:{
				//type: 'ajax',
				//url: 'caseList2.txt',
				type: 'rest',
				url: 'http://' + ipPort + '/bpccasestree',
				reader: {
		            type: 'json',
		            root: 'Catalog'
		        }
			}
		});
		var conv = function(nodes){
			var res = [];
			if (Object.prototype.toString.apply(nodes) != '[object Array]')
				nodes = [nodes];
			for(var idx in nodes){
				var node = nodes[idx];8
				var ele = {text:node.name}; //{id:node.raw.id, text:node.raw.text, cls:node.raw.cls };
				if (node.type && node.type==1){
					ele.id = 'P' + node.id;
					ele.cls = 'folder';
					ele.expanded = true;
					ele.children = conv(node.cases);
				}
				else{
					ele.id = 'C' + node.id;
					ele.leaf = true;
					ele.checked = false;
				}
				res[res.length] = ele;
			}
			return res;
		};
		var s2 = Ext.create('Ext.data.TreeStore',{
			data: []
		});
		Ext.apply(this, {
			autoScroll: true,
		    rootVisible: true,
			height: '100%',
			dockedItems: [{
                xtype: 'toolbar',
                dock: 'top',
                items: [{
                    text: 'Report',
                    handler: function() {
                    	var reportUI = Ext.create('case.report', {});
							reportWin = Ext.create('Ext.window.Window', {
							title: 'Report',
							closable: true,
							//closeAction: 'hide',
							width: 800,
							height: 500,
							//layout: 'border',
							borderStyle: 'padding:5px;',
							shadown: false,
							modal: true,
							items: [
								reportUI
							]
						});
						
						reportWin.show(this, function(){
						});
						reportWin.setLoading('Loading report');
                    }
                },{
                    text: 'Run selected',
                    handler: function() {
                    	if (caseList.dockedItems.items[1].items.items[4].value == null){
                    		alert('Please select a server!');
                    		return;
                    	};
                    	me_list.onRunSelected();
                    }
                },{
                    text: 'Run all',
                    handler: function() {
                    	if (caseList.dockedItems.items[1].items.items[4].value == null){
                    		alert('Please select a server!');
                    		return;
                    	};
                    	statusScreen.setLoading('Loading', true);
                    	var rootNode = me_list.getRootNode();
                    	if (!(rootNode)){
                    		alert('Please wait until test data is loaded.');
                    		statusScreen.setLoading(false);
                    		return;
                    	}
                    	var catalogCount = rootNode.childNodes.length;
            			for (m = 0; m < catalogCount; m++){
            				var caseCount = rootNode.childNodes[m].childNodes.length;
            				for (n = 0; n < caseCount; n++){
            					// get testcaseid
            					var sid = rootNode.childNodes[m].childNodes[n].data.id;
            					var caseId = sid.substring(1, sid.length);
            					me_list.runTestCase(caseId);
            				};
            			}
                    }
                },{
					text: 'Settings',
					handler: function() {
						//var server = Ext.create('server', {});
					/*	var settingWin = Ext.create('Ext.window.Window', {
							title: 'Settings',
							closable: true,
							//closeAction: 'hide',
							width: 800,
							height: 400,
							//layout: 'border',
							borderStyle: 'padding:5px;',
							shadown: false,
							modal: true,
							items: [
							     settingServer
							]
						});*/
						settingWin.show(this, function(){
						});
					}
				},{
		        	xtype: 'combobox',
		        	store: me_list.serverStore,
		        	emptyText: 'Select Server',
		        	width: 100,
		        	displayField: 'name',
		            valueField: 'id'
		        }]
			}],
			store: s2/*,
			root: {
				text: 'BPC 10 NW API Test Cases',
				expanded: true,
				children : []
			}*/
		});
		me_list.caseStore.on('load', function(p1,p2,p3) {
			var ns = [];
			for(var idx in p3){
				ns[ns.length] = p3[idx].raw;
			}
			var ch = conv(ns);
			var r = {
					text: 'BPC 10 NW API Test Cases',
					id: '__root__',
					expanded: true,
					children : ch
				};
			s2.setRootNode(r);
			me_list.setLoading(false);
		});
		me_list.caseStore.load();
		//tStore.load();
		this.callParent(arguments);
		
		this.on('itemcontextmenu', this.onContextMenu, this);
		this.on('itemdblclick', this.onDblClick, this);
		me_list.setLoading(false);
	},
	
	onDblClick: function(view, rec, node, idx, e){
		if (rec.get('leaf')){
			var sid = rec.get('id');
			var id = sid.substring(1, sid.length);
			caseDetail.load(id);
			caseDetail.enable();
		}
	},
	
	onContextMenu: function(view, rec, node, idx, e){
		//node.select();
		var mnuRefresh = Ext.create('Ext.Action', {
		    text: 'Refresh',
		    disabled: true,
		    handler: this.onRefresh
		});
		var mnuAddCatalog = Ext.create('Ext.Action', {
		    text: 'Add Catalog',
		    disabled: true,
		    handler: this.onAddCatalog
		});
		var mnuAddCase = Ext.create('Ext.Action', {
		    text: 'Add Case',
		    disabled: true,
		    handler: this.onAddCase
		});
		var mnuRename = Ext.create('Ext.Action', {
			text: 'Rename',
			disabled: true,
			handler: this.onRename
		});
		var mnuDelete = Ext.create('Ext.Action', {
		    text: 'Delete',
		    disabled: true,
		    handler: this.onDelete
		});
		var mnuRun = Ext.create('Ext.Action', {
		    text: 'Run',
		    disabled: true,
		    handler: this.onRun
		});
		var mnuRunAll = Ext.create('Ext.Action', {
		    text: 'Run all',
		    disabled: true,
		    handler: this.onRunAll
		});
		if (rec.get('leaf')){
			mnuDelete.setDisabled(false);
			mnuRun.setDisabled(false);
			mnuRename.setDisabled(false);
		}
		else{
			if (rec.get('id')=='__root__') {
				mnuRefresh.setDisabled(false);
				mnuAddCatalog.setDisabled(false);
				mnuRunAll.setDisabled(false);
			}
			else {
				mnuAddCase.setDisabled(false);
				mnuRename.setDisabled(false);
				mnuRunAll.setDisabled(false);
			}
			mnuDelete.setDisabled(false);
		}
	    var contextMenu = Ext.create('Ext.menu.Menu', {
	        items: [
	            mnuRefresh,
	            '-',
				mnuAddCatalog,
				mnuAddCase,
				'-',
				mnuRename,
				'-',
				mnuDelete,
				'-',
				mnuRun,
				mnuRunAll
	        ]
	    });
	    e.stopEvent();
        contextMenu.showAt(e.getXY());
        return false;
	},
	onRefresh: function() {
		var me_caselist = caseList;
		me_caselist.setLoading('Loading');
		me_caselist.caseStore.load();
	},
	onAddCatalog: function(p1,p2,p3,p4){
		var me_caselist = caseList;
		Ext.Msg.prompt('Name', 'Please input new catalog name:', function(btn, text) {
			if (btn=='ok'){
				var catalog = Ext.ModelManager.create({id:'0', name:text}, 'Catalog');
                catalog.phantom = false;
        		me_caselist.setLoading('Adding Catalog');
				catalog.save({
					success: function(catalog, operation){
						var selNode = me_caselist.getSelectionModel().getLastSelected( );
						selNode.expand(null, function() {
							var newNodeCfg = {
									text : catalog.get('name'),
									id : 'P' + catalog.get('id'),
									cls: 'folder',
									children: []
							}
							var newNode = selNode.insertBefore(newNodeCfg, selNode.firstChild);
							//me.treeEditor.editNode = newNode;
							//me.treeEditor.startEdit(newNode.ui.textNode);
						}, me_caselist);
					},
					failure: function(catalog, operation) {
						Ext.Msg.alert('error', operation.error);
					},
					callback: function() {
						me_caselist.setLoading(false);
					}
				});
			}
		});
	},
	onAddCase: function(){
		var me_caselist = caseList;

		/*
		var lurl = 'http://10.59.48.70:9999/AT/caseLoad.jsp';
		//alert(lurl);
		Ext.Ajax.request({
			url: lurl,
			//url: 'http://www.baidu.com',
			method: 'POST',
			//subCaseId: '11111111111111111111111111',
			success: function(response){
				alert('good');
			}
		});
		*/
		
		Ext.Msg.prompt('Name', 'Please input new case name:', function(btn, text) {
			if (btn=='ok'){
				
				var selNode = me_caselist.getSelectionModel().getLastSelected( );
				var sid = selNode.get('id');
				var id = sid.substring(1, sid.length);
				var caseDetail = Ext.ModelManager.create({id:'0', name:text, catalogId:id, steps:[{name:'step1', request: 'null', response: 'null\(if no response\, please delete this line\)'}], subcases:[{name:'subcase1',params:[]}]}, 'CaseDetail');
                caseDetail.phantom = false;
        		me_caselist.setLoading('Adding Case');
        		/*Ext.Ajax.request({
            		url: 'http://' + ipPort + '/BpcTesterWeb/bpcsaveserver/' + serverId,
            		method: 'PUT',
            		jsonData: jsonStr,
        		
        		var myObj = {Server:
				{                    	
				id: serverId,
				hostUrl: hostUrl,
				hostServer: hostServer,
				name: name,
				isDailyRun: isDailyRun,
				runSchedule: runSchedule,
				user: user,
				password: password
				}	
};
var jsonStr = Ext.encode(myObj);

Ext.Ajax.request({
	url: 'http://' + ipPort + '/BpcTesterWeb/bpcsaveserver/' + serverId,
	method: 'PUT',
	jsonData: jsonStr,
	success: function(response){
*/
		
				caseDetail.save({
					success: function(caseDetail, operation){
						selNode.expand(null, function() {
							var newNodeCfg = {
									text : caseDetail.get('name'),
									id : 'C' + caseDetail.get('id'),
									leaf: true,
									checked: false
							}
							var newNode = selNode.insertBefore(newNodeCfg, selNode.firstChild);
							//me.treeEditor.editNode = newNode;
							//me.treeEditor.startEdit(newNode.ui.textNode);
						}, me_caselist);
					},
					failure: function(caseDetail, operation) {
						
						Ext.Msg.alert('error', 'ERROR');
						
						Ext.Msg.alert('error', 'ERROR');
					},
					callback: function() {
						me_caselist.setLoading(false);
					}
				});			
			}
		});
	},
	onRename: function(){
		var me_list = caseList;
		Ext.Msg.prompt('Name', 'Please input new name:', function(btn, text) {
			if (btn=='ok'){
				var selNode = me_list.getSelectionModel().getLastSelected( );
				var rec;
				var sid = selNode.data.id;
				var id = sid.substring(1, sid.length);
				if (selNode.get('leaf')){
				/*	Ext.Msg.alert('unsupported', 'not support to rename case');
					return;*/
					var catId = selNode.parentNode.data.id;
					catId = catId.substring(1,catId.length);
					var CaseDetail = Ext.ModelManager.getModel('CaseDetail');
					CaseDetail.load(id, {
						success: function(detail){
							var rec = 
								Ext.ModelManager.create({name:text, id:id , catalogId:catId, profilegroupId:detail.data.profilegroupId}, 'CaseDetail');
							me_list.setLoading('Renaming');
							rec.save({
								success: function(rec, operation){
//									selNode.set('id', rec.get('id'));
									selNode.set('text', rec.get('name'));
								},
								failure: function(caseDetail, operation) {
									Ext.Msg.alert('error', operation.error);
								},
								callback: function() {
									me_list.setLoading(false);
								}
							});
							
						}
					});	
					
					
				}
				else {
					var rec = Ext.ModelManager.create({name:text, id:id}, 'Catalog');
					me_list.setLoading('Renaming');
					rec.save({
						success: function(rec, operation){
//							selNode.set('id', rec.get('id'));
							selNode.set('text', rec.get('name'));
						},
						failure: function(caseDetail, operation) {
							Ext.Msg.alert('error', operation.error);
						},
						callback: function() {
							me_list.setLoading(false);
						}
					});
				}
							
			}
		});
	},
	onDelete: function(){
		var me_list = caseList;
		var yes = false;
		Ext.Msg.show({title:'Delete', 
			msg:'Do you want to delete?',
			buttons: Ext.Msg.YESNO,
			icon: Ext.window.MessageBox.QUESTION,
			fn: function(btn, text) {
				if (btn=='yes'){
					var selNode = me_list.getSelectionModel().getLastSelected( );
					var rec;
					var sid = selNode.get('id');
					var id = sid.substring(1, sid.length);
					if (selNode.get('leaf')){
						var rec = Ext.ModelManager.create({name:selNode.data.text, id:id}, 'CaseDetail');
					}
					else {
						var rec = Ext.ModelManager.create({name:selNode.data.text, id:id}, 'Catalog');
					}
					me_list.setLoading('Deleting');
					rec.destroy({
						success: function(rec, operation){
							selNode.parentNode.removeChild(selNode);
						},
						failure: function(caseDetail, operation) {
							Ext.Msg.alert('error', operation.error);
						},
						callback: function() {
							me_list.setLoading(false);
						}
					});
				}
		}});
	},
	onRun: function(){
    	if (caseList.dockedItems.items[1].items.items[4].value == null){
    		alert('Please select a server!');
    		return;
    	};
		statusScreen.setLoading('Loading', true);
		var me_list = caseList;
		var selNode = me_list.getSelectionModel().getLastSelected( );
		// get testcaseid
		var sid = selNode.get('id');
		var caseId = sid.substring(1, sid.length);
		me_list.runTestCase(caseId);
	},
	onRunAll: function(){
    	if (caseList.dockedItems.items[1].items.items[4].value == null){
    		alert('Please select a server!');
    		return;
    	};
		statusScreen.setLoading('Loading', true);
		var me_list = caseList;
		var selNode = me_list.getSelectionModel().getLastSelected( );
		if (selNode.isRoot()){ // run all tests for the product
			var catalogCount = selNode.childNodes.length;
			for (m = 0; m < catalogCount; m++){
				var caseCount = selNode.childNodes[m].childNodes.length;
				for (n = 0; n < caseCount; n++){
					// get testcaseid
					var sid = selNode.childNodes[m].childNodes[n].data.id;
					var caseId = sid.substring(1, sid.length);
					me_list.runTestCase(caseId);
				};
			}
		} else { // run all tests of the selected catalog
			var caseCount = selNode.childNodes.length;
			for (n = 0; n < caseCount; n++){
				// get testcaseid
				var sid = selNode.childNodes[n].data.id;
				var caseId = sid.substring(1, sid.length);
				me_list.runTestCase(caseId);
			};
		};	
	},
	onRunSelected: function(){
    	if (caseList.dockedItems.items[1].items.items[4].value == null){
    		alert('Please select a server!');
    		return;
    	};
		statusScreen.setLoading('Loading', true);
		var me_list = caseList;
		var selNodes = new Array;
		selNodes = me_list.getChecked();
		if (selNodes.length == 0){
			alert('Please select at least one test case.');
			statusScreen.setLoading(false);
			return;
		};
		for (n = 0; n < selNodes.length; n++){
			var sid = selNodes[n].get('id');
			var caseId = sid.substring(1, sid.length);
			me_list.runTestCase(caseId);
		};
	},	
	runTestCase: function(caseId){
    	if (caseList.dockedItems.items[1].items.items[4].value == null){
    		alert('Please select a server!');
    		return;
    	};
		// get testcasedata
		var url = 'http://' + ipPort + '/bpccase/' + caseId;
		Ext.Ajax.request({ 
			url: url,
			method: 'GET',
			success: function(response){
				var caseData = Ext.decode(response.responseText);
				var caseName = caseData.name;
				var caseId = caseData.id;
				var subcases = new Array;
				if (!(caseData.subcases.length)){
					subcases[0] = caseData.subcases;
				} else {
					subcases = caseData.subcases;
				};
				for (i = 0; i < subcases.length; i++){
					var subCaseId = subcases[i].id;
					if (subCaseNames[subCaseId]){
						alert (caseName + ' is already running');
						statusScreen.setLoading(false);
						return;
					};
					subCaseNames[subCaseId] = subcases[i].name;
					statusScreen.setLoading(false);
					caseDetail.runSubCase(caseId, subCaseId, caseName, subCaseNames[subCaseId]);
				};

				// add row for subcase to statuspanel
//				statusScreen.addRow(caseId, subCaseId, caseName, subCaseNames[subCaseId]);
				
//				};
//				if (caseData.subcases.length){
//					var subCaseCount = caseData.subcases.length;
//				} else { // no array if only one subcase
//					var subCaseCount = 1;
//				};
//				for (i = 0; i < subCaseCount; i++){
//					if (subCaseCount == 1){ // no array
//						var subCaseId = caseData.subcases.id;
//						// for a running subcase the name is stored in subCaseName[] at subCaseId
//						if (subCaseNames[subCaseId]){
//							alert (caseName + ' is already running');
//							statusScreen.setLoading(false);
//							return;
//						};
//						subCaseNames[subCaseId] = caseData.subcases.name;
//					} else {
//						var subCaseId = caseData.subcases[i].id;
//						if (subCaseNames[subCaseId]){
//							alert (caseName + ' is already running');
//							statusScreen.setLoading(false);
//							return;
//						};
//						subCaseNames[subCaseId] = caseData.subcases[i].name;
//					};
//					statusScreen.setLoading(false);
//					// add row for subcase to statuspanel
//					statusScreen.addRow(caseId, subCaseId, caseName, subCaseNames[subCaseId]);
//					
//					caseDetail.runSubCase(caseId, subCaseId, caseName, subCaseNames[subCaseId]);
//				};
			},
			failure: function() {
			},
			callback: function() {
			}
		}); 
	}
	
	/*
	autoLoad: true,
	root: {
		text : 'BPC 10 NW API Test Cases',
		expanded: true,
		children : [{
			text : 'Mock Module 1', 
			leaf : false
		},{
			text : 'Mock Module 2', 
			leaf : false
		},{
			text : 'Mock Module 333', 
			children : [{
				text : 'Mock Sub Module 3.1', 
				children : [{
					text : 'Test Case 1', 
					leaf : true
				}]
			}]
		}]
	}
	*/
});
